<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>日期数组</title>
</head>
<body>
<script>
    //todo； 日期数组排序比较简单，我们可以使用内置的排序方法就能轻松解决
    const dates = [
        new Date('July 20, 2021 20:17:40'),
        new Date('August 19, 2021 23:15:30'),
        new Date('March 13, 2021 04:20'),
        new Date('October 2, 2021 11:05')
    ];
    dates.sort((date1, date2) => date1 - date2);

    /*
    [
      2021-03-13T09:20:00.000Z,
      2021-07-21T00:17:40.000Z,
      2021-08-20T03:15:30.000Z,
      2021-10-02T15:05:00.000Z
    ]
    */
    // dates1;
    console.log('%c   dates: ', 'color: MidnightBlue; background: Aquamarine; font-size: 20px;', dates);

    //todo： 按照对象的日期属性排序

    // 同样，按照对象的日期属性排序也很简单，同样我们可以使用上述的内置 sort() 方法

    const d1 = new Date('2019-06-01');
    const d2 = new Date('2018-06-01');
    const d3 = new Date('2019-06-01');

    const objects = [
        {createdAt: d1, name: 'Test 1'},
        {createdAt: d2, name: 'Test 2'},
        {createdAt: d3, name: 'Test 3'}
    ];

    objects.sort((a, b) => a.createdAt - b.createdAt);

    // [ 'Test 2', 'Test 1', 'Test 3' ]
    // console.log(objects.map(o => o.name));
    console.log('%c   objects.map(o => o.name): ', 'color: MidnightBlue; background: Aquamarine; font-size: 20px;', objects.map(o => o.name));

    //todo：去除时间按日期排序

    // 有时候，你只需要按照日期排序，需要忽略日期的时间部分，这时你需要借助 [setHours()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours)  方法，

    const dates1 = [
        new Date('July 20, 2021 20:17:40'),
        new Date('August 19, 2021 23:15:30'),
        new Date('July 20, 2021 23:15:30'),
        new Date('August 19, 2021 20:17:40')
    ];

    // `setHours(0, 0, 0, 0)` zeroes out hours, minutes, seconds, and milliseconds
    dates1.sort((date1, date2) => new Date(date1).setHours(0, 0, 0, 0) - new Date(date2).setHours(0, 0, 0, 0));
    console.log('%c   dates: ','color: MidnightBlue; background: Aquamarine; font-size: 20px;', dates1);

    /*
    [
      2021-07-21T00:17:40.000Z,
      2021-07-21T03:15:30.000Z,
      2021-08-20T03:15:30.000Z,
      2021-08-20T00:17:40.000Z
    ]
    */
    // dates1;
</script>
</body>
</html>